<?php

/**
 * 会员中心
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

/* 载入语言包 */  
require(ROOT_PATH . 'languages/zh_cn/user.php');

$user_id = $_SESSION['user_id'];
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';

$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$back_act='';    

// 不需要登录的操作或自己验证是否登录（如ajax处理）的act
$not_login_arr =
array('login','complete',  'change_password', 'detect_captcha','act_login','register','act_register','act_edit_password','get_password','send_pwd_email','password', 'signin', 'add_tag', 'collect', 'return_to_cart', 'logout', 'email_list', 'validate_email', 'send_hash_mail', 'order_query', 'is_registered', 'check_email','clear_history','qpassword_name', 'get_email', 'check_answer');

/* 显示页面的action列表 */
$ui_arr = array('dellookat','complete','change_password','detect_captcha','join_list','join_detail','register', 'login', 'profile', 'profile_pass', 'order_list', 'order_detail', 'addressList', 'collectionList',
'message_list', 'tag_list', 'get_password', 'reset_password', 'booking_list', 'add_booking', 'account_raply','message',
'account_deposit', 'account_log', 'account_detail', 'act_account', 'pay', 'default', 'bonus', 'group_buy', 'group_buy_detail', 'affiliate', 'comment_list','validate_email','track_packages', 'transform_points','qpassword_name', 'get_email', 'check_answer' ,'void_join', 'mobile_validated', 'validated_mobile');

/* 未登录处理 */
if (empty($_SESSION['user_id']))
{
    if (!in_array($action, $not_login_arr))
    {
        if (in_array($action, $ui_arr))
        {
            if (!empty($_SERVER['QUERY_STRING']))
            {
                $back_act = 'user.php?' . strip_tags($_SERVER['QUERY_STRING']);
            }
            $action = 'login';
        }
        else
        {
            //未登录提交数据。非正常途径提交数据！
            errorMsg($_LANG['require_login']);
        }
    }
}

/* 用户注册 */
if ($action == 'register')
{
    /** 载入会员中心相关函数 **/
    include_once(ROOT_PATH . 'includes/lib_passport.php');    
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $email    = isset($_POST['email']) ? trim($_POST['email']) : '';

    if (strlen($username) < 6)
    {
        errorMsg($_LANG['passport_js']['username_shorter']);
    }
    if (strlen($password) < 6)
    {
        errorMsg($_LANG['passport_js']['password_shorter']);
    }
    if (strpos($password, ' ') > 0)
    {
        errorMsg($_LANG['passwd_balnk']);
    }

    if (register($username, $password, $email) !== false)
    {
        //注册成功
        $userinfo = array('userId'=>$_SESSION['user_id'], 'userName'=>urlencode($_SESSION['user_name']));
        $response = array('response'=>'register', 'userinfo'=>$userinfo);
        echo tourldecode($response);
    }
    else
    {
        errorMsg('注册失败');
    }
}

/* 用户登录 */
elseif ($action == 'login')
{
    $username = !empty($_POST['username']) ? trim($_POST['username']) : '';
    $password = !empty($_POST['password']) ? trim($_POST['password']) : '';

    if(!$username){
        errorMsg('请输入用户名');
    }
    if(!$password){
        errorMsg('请输入密码');
    }

    if ($user->login($username, $password))
    { 
        update_user_info();  //更新用户最后登录信息
        $user_all_info = get_user_info();
        
        $userinfo = array('userId'=>$user_all_info['user_id'], 'userName'=>urlencode($user_all_info['user_name']));
        $response = array('response'=>'login', 'userinfo'=>$userinfo);
        echo tourldecode($response);
    }
    else
    {
        errorMsg('用户名或密码错误');
    }
}

/* 用户注销 */
elseif ($action == 'logout')
{
    $user->logout();
    $response = array('respone' =>'logout');
    echo json_encode($response);
}

/* 查看订单列表 */
elseif ($action == 'orderList')
{
    // include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH .'includes/lib_order.php');
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE join_id=0 AND user_id = '$user_id'");  
    $orders = get_user_orders($user_id);
    $response = array('response'=>'orderList', 'orderList'=>$orders, 'orderListCount'=>$record_count);
    echo tourldecode($response);
}

/* 查看订单详情 */
elseif ($action == 'orderDetail')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    //include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $order_id = isset($_POST['orderId']) ? intval($_POST['orderId']) : 0;

    /* 订单详情 */
    $order = get_order_detail($order_id, $user_id);

    if ($order === false)
    {
        errorMsg($_LANG['back_home_lnk']);

        exit;
    }

    /* 订单商品 */
    $goods_list = order_goods($order_id);

    foreach ($goods_list AS $key => $value)
    {
        $goods_list[$key]['market_price'] = price_format($value['market_price'], false);
        $goods_list[$key]['goods_price']  = price_format($value['goods_price'], false);
        $goods_list[$key]['subtotal']     = price_format($value['subtotal'], false);
    }

    /** 支付暂时不做  **/

    // /* 未发货，未付款时允许更换支付方式 */
    // if ($order['order_amount'] > 0 && $order['pay_status'] == PS_UNPAYED && $order['order_status'] == OS_UNCONFIRMED && $order['shipping_status'] == SS_UNSHIPPED)
    // {
    //     $payment_list = available_payment_list(1, 0, false);

    //     /* 过滤掉当前支付方式和余额支付方式 */
    //     if(is_array($payment_list))
    //     {
    //         foreach ($payment_list as $key => $payment)
    //         {
    //             if ($payment['pay_id'] == $order['pay_id'] || $payment['pay_code'] == 'balance')
    //             {
    //                 unset($payment_list[$key]);
    //             }
    //             if($payment['pay_id'] == 3 && $order['surplus'] > 0){
    //                 unset($payment_list[$key]);
    //             }
    //         }
    //     }
    //     $smarty->assign('payment_list', $payment_list);

    // }

    /* 订单 支付 配送 状态语言项 */
    $order['order_status_name'] = $_LANG['os'][$order['order_status']];
    $order['pay_status_name'] = $_LANG['ps'][$order['pay_status']];
    $order['shipping_status_name'] = $_LANG['ss'][$order['shipping_status']];
    $province = $order['province']?selectaddress($order['province'])." ":'';
    $city = $order['city']?selectaddress($order['city'])." ":'';
    $district = $order['district']?selectaddress($order['district'])." ":'';
    $address = $order['address'];
    $order['addr'] = $province . $city . $district;

    var_dump($order);
    echo "++++++++++++++++++++++++++++++++++++++++++";
    echo "+++++++++     商品列表      ++++++++++++";
    echo "++++++++++++++++++++++++++++++++++++++++++";
    var_dump($goods_list);
}

/* 取消订单 */
elseif ($action == 'orderCancel')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');

    $order_id = isset($_POST['orderId']) ? intval($_POST['orderId']) : 0;
    $order=order_info($order_id);

    $goods_list=order_goods($order_id);
    if (cancel_order($order_id, $user_id))
    {
        // 取消订单增加库存
        foreach ($goods_list as $key => $value) {
        $sql = "SELECT goods_number FROM " . $ecs->table('goods_stock') . " WHERE goods_id=" . $value['goods_id'];
        $number=$db->getOne($sql);
        $number=intval($number)+$value['goods_number'];
        $sql = "UPDATE " .$GLOBALS['ecs']->table('goods_stock').
                            " SET goods_number = '$number' WHERE  goods_id=" . $value['goods_id'];
        $db->query($sql);
        }
        $response = array('response'=>'orderCancel');
        echo json_encode($response);
        exit;
    }
    else
    {
        errorMsg($_LANG['order_list_lnk']);
    }

}

/* 个人资料页面 */
elseif ($action == 'profile')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $profile = get_profile($user_id);

    $profile = tourlencode($profile);
    $response = array('response' => 'profile', 'profile' => $profile);  
    echo tourldecode($response);

}

/*  上传头像 */


/* 修改个人资料的处理 */
elseif ($action == 'editProfile')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');

    $other['head_url']   = $real_name = isset($_POST['head_url']) ? trim($_POST['head_url']) : '';
    $other['real_name']   = $real_name = isset($_POST['real_name']) ? trim($_POST['real_name']) : '';
    $other['sex']         = $sex = isset($_POST['sex']) ? trim($_POST['sex']) : '';
    $other['birthday']    = $birthday = trim($_POST['birthdayYear']) .'-'. trim($_POST['birthdayMonth']) .'-'. trim($_POST['birthdayDay']);
    $other['email']       = $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $other['school_name'] = $school_name = isset($_POST['school_name']) ? trim($_POST['school_name']) : '';
    $other['camp']        = $camp = isset($_POST['camp']) ? trim($_POST['camp']) : '';
    $other['studio']      = $studio = isset($_POST['studio']) ? trim($_POST['studio']) : '';
    $other['picture_age'] = $picture_age = isset($_POST['picture_age']) ? trim($_POST['picture_age']) : '';
    $other['qq']          = $qq = isset($_POST['qq']) ? intval($_POST['qq']) : '';
    $other['mobile_phone']= $mobile_phone = isset($_POST['mobile_phone']) ? trim($_POST['mobile_phone']) : '';
    $other['signature']   = $signature = isset($_POST['signature']) ? trim($_POST['signature']) : '';
    $other['hobby']       = $hobby = isset($_POST['hobby']) ? trim($_POST['hobby']) : '';

    
    //更新个人资料
    $sql = 'UPDATE ' . $ecs->table('user_info') . " SET `real_name`='$real_name', `sex`='$sex', `birthday`='$birthday', `school_name`='$school_name', `camp`='$camp', `studio`='$studio', `picture_age`='$picture_age',  `qq`='$qq', `signature`='$signature', `hobby`='$hobby' WHERE `user_id`='" . $_SESSION['user_id'] . "'";
    $db->query($sql);
    $sql2 = 'UPDATE ' . $ecs->table('users') . " SET `mobile_phone`='$mobile_phone' WHERE `user_id`='" . $_SESSION['user_id'] . "'";
    $db->query($sql2);

    $response = array('response' => 'editProfile');
    
}

/* 收藏商品 */
elseif ($action == 'collect')
{
    $goods_id = $_REQUEST['id'];

    if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0)
    {
        errorMsg($_LANG['login_please']);
    }
    else
    {
        /* 检查是否已经存在于用户的收藏夹 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('collect_goods') .
            " WHERE user_id='$_SESSION[user_id]' AND goods_id = '$goods_id'";
        if ($GLOBALS['db']->GetOne($sql) > 0)
        {
            errorMsg($GLOBALS['_LANG']['collect_existed']);
        }
        else
        {
            $time = gmtime();
            $sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" .
                    "VALUES ('$_SESSION[user_id]', '$goods_id', '$time')";

            if ($GLOBALS['db']->query($sql) === false)
            {
                errorMsg( $GLOBALS['db']->errorMsg() );
            }
            else
            {
               $response = array('response' => 'goodsCollect');
               echo json_encode($response);
               //$GLOBALS['_LANG']['collect_success'];
            }
        }
    }
}

/* 显示收藏商品列表 */
elseif ($action == 'collectionList')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $pagesize = 10;

    $count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('collect_goods').
                                " WHERE user_id='$user_id' ORDER BY add_time DESC");
    if ($count === 0) {
        errorMsg('没有收藏商品');
    }
    if ($count !==0 && $count >= ($page-1) * $pagesize) {            
        $goodsList = get_collection_goods($user_id, $pagesize, ($page-1) * $pagesize);
        $response = array('response' => 'collectionList', 'goodsList' => $goodsList, 'goodsCount' => $count);
        echo tourldecode($response);
    }
    else{
        errorMsg('分页不存在');
    }
}

/* 收货地址列表界面*/
elseif ($action == 'addressList')
{
    include_once(ROOT_PATH . 'languages/zh_cn/shopping_flow.php');

    /* 获得用户所有的收货人信息 */
    $consignee_list = get_consignee_list($_SESSION['user_id']);
    $count=count($consignee_list);
    echo $count;
    var_dump($consignee_list);
    
    /* 获取默认收货ID */
    $address_id  = $db->getOne("SELECT address_id FROM " .$ecs->table('users'). " WHERE user_id='$user_id'");
    echo $address_id;
}

/* 添加/编辑收货地址的处理 */
elseif ($action == 'editAddress')
{
   
}
?>